import Vue from 'vue'
import Vuex from 'vuex'
import { userLogin, cityDetail } from '../api/api/user'
var WebIM = require("../utils/WebIM")["default"];
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		imLogin:false,
		xzHouse: {},
		text: "",
		name: "",
		plicname: "",
		community_id: 0,
		guard_id: 0,
		cache: null,
		address: uni.getStorageSync('address'),//用户的位置信息
		userInfor: uni.getStorageSync('userInfor'),
		checkLogin: uni.getStorageSync('token') ? true : false,
		city_code: uni.getStorageSync('city_code'),//城市id object
	},


	mutations: {
		//缓存页面选中值
		changeCache(state, value) {
			state.cache = value
		},
		changeAddressInfor(state, value) {
			state.address = value
		},
		//保存用户信息
		setUserInfor(state, value) {
			state.userInfor = value
		},
		//改变登录状态
		changeCheckLogin(state, value) {
			state.checkLogin = value
		},
		//改变城市code
		changeCity_code(state, value){
			state.city_code = value
		},
		//设置选中那个房源
		setbeforhouse(state, value){
			state.xzHouse = value
		}
	},
	actions: {
		//缓存页面选中值
		CHANGCATCH({ commit }, value) {
			return new Promise((resole, reject) => {
				try {
					commit('changeCache', value)
				} catch (e) {
					debugger
					reject(e)
				}
				resole()
			})
		},
		//获取页面选中值 //并且晴空
		GETCACHE({ commit, rootState }, value) {
			return new Promise((resole, reject) => {
				if (rootState.cache) {
					// const passData = JSON.parse(JSON.stringify(rootState.cache))
					// commit('changeCache', null)
					resole(rootState.cache)
				} else {
					reject()
				}
			})
		},

		//获取微信经纬度
		SYSCHANGEADDRESS({ commit, rootState }) {
			return new Promise((resole, reject) => {
				uni.showLoading({
					title: '获取中'
				});
				if (!rootState.address.adcode) {
					uni.authorize({
						scope: "scope.userLocation",
						complete: () => {
							uni.getLocation({
								type: 'wgs84',
								geocode: true,
								complete: (data) => {
									debugger
									// debugger
									if (data.errMsg != "getLocation:ok") {
										data.latitude = '30.648513'
										data.longitude = '104.062357'
									}
									console.log(data)
									// debugger
									// console.log(data,'位置信息')
									uni.request({
										url: 'https://apis.map.qq.com/ws/geocoder/v1', //仅为示例，并非真实接口地址。
										method: 'GET',
										data: {
											location: `${data.latitude},${data.longitude}`,
											key: 'ZWEBZ-R7N3U-BJSVH-4TCR3-66MDQ-S3FDJ'
										},
										success: (res) => {
											uni.hideLoading();
											debugger
											console.log(res.data.result.ad_info)
											res.data.result.ad_info.mycitycode = res.data.result.ad_info.city_code.substr(3, 8) //adcode
											res.data.result.ad_info.latitude = res.data.result.ad_info.location.lat //adcode
											res.data.result.ad_info.longitude = res.data.result.ad_info.location.lng //adcode
											var reg = new RegExp("市", "g");
											res.data.result.ad_info.city = res.data.result.ad_info.city.replace(reg, "");
											uni.setStorageSync('address', res.data.result.ad_info);
											commit('changeAddressInfor', res.data.result.ad_info)
											// debugger
											return resole()
										},
										// fail: err => {
										// 	uni.hideLoading();
										// 	uni.showTabBar({
										// 		title: '接口获取地理位置异常',
										// 		icon: 'none'
										// 	})
										// 	return reject(err)
										// }
									});
									// commit('changeAddress', {latitude: data.latitude, longitude: data.longitude})
									// return resole({latitude: data.latitude, longitude: data.longitude})
								},
								fail: (err) => {
									console.log(err)
								}
							});
						},
						fail: (err) => {
							// debugger
							// uni.hideLoading();
							// return reject(err)
						}
					});
				} else {
					uni.hideLoading();
					return resole()
				}
			})
		},
		//授权登录
		checkLogin({ commit }) {
			// return new Promise((resole, reject) => {
			// return 
			uni.showModal({
				title: '温馨提示',
				content: '亲，授权微信登录后才能正常使用小程序功能',
				success(res1) {
					//如果用户点击了确定按钮
					if (res1.confirm) {
						uni.getUserProfile({
							desc: "获取你的昵称、头像、地区及性别",
							success: (userInfor) => {
								commit('setUserInfor', userInfor.userInfor)
								uni.setStorageSync("userInfor", userInfor.userInfor);
								uni.login({
									success: code => {
										let data = {
											code: code.code,
											nickname: userInfor.userInfo.nickName
										}
										userLogin(data).then((res) => {
											console.log(res.data.im);
											uni.setStorageSync("token", res.data.token);
											getApp().globalData.conn.open({
												apiUrl: WebIM.config.apiURL,
												user: res.data.im.name,
												//   user: "opp123",
												pwd: res.data.im.password,
												//   grant_type: "password",
												appKey: WebIM.config.appkey,
												success: () => {
													uni.setStorageSync("myUsername", res.data.im.nickname);
													uni.hideLoading();
													uni.showToast({
														title: '授权成功',
														duration: 2000
													});
												}
											});
										});
									}
								})
							},
							fail: (res) => {
								console.log(2);
								console.log(res);
								//拒绝授权
								uni.showToast({
									title: "您拒绝了请求,不能正常使用小程序",
									icon: "error",
									duration: 2000,
								});
								return;
							},
						});
					} else if (res.cancel) {
						//如果用户点击了取消按钮
						console.log(3);
						uni.showToast({
							title: '您拒绝了请求,不能正常使用小程序',
							icon: 'error',
							duration: 2000
						});
						return;
					}
				}
			});

			// })

		},
		//city_code换取城市详情
		getCityDetail({ commit, rootState }) {
			return new Promise((resole, reject) => {
				if (rootState.city_code) {
					return resole(rootState.city_code)
				}
				cityDetail({city_code: rootState.address.mycitycode}).then(res => {
					commit('changeCity_code', res.data)
					uni.getStorageSync('city_code', res.data)
					return resole(res.data)
				}).catch(() => {
					reject()
				})
			})
		},
		SETBEFORHOUSE({commit, rootState}, obj){
			commit('setbeforhouse', obj)
		},
		GETBEFORHOUSE({commit, rootState}){
			new Promise((solve, reject)=>{
				if(JSON.stringify(rootState.xzHouse) != '{}'){
					return solve(rootState.xzHouse)
				}else{
					return reject()
				}
			})
		}
	}
})
export default store